<template>
  <div class="alphabet">
   <ul class="list">
     <li class="item" v-for="item of letters" :key="item" :ref="item" @click="handleLetterClick" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">{{item}}</li>
   </ul>
  </div>
</template>
<script>
export default {
  name: 'cityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null// 用于控制时间节流
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop//  字母A距离顶部的高度
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }// ['A','B','C'...]
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)//  向外触发事件，事件名为change,事件携带的信息为e.target.innnerText
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79//  手指触摸的地方距离顶部的高度  79是顶部搜索部分的高度
          const index = Math.floor((touchY - this.startY) / 20)//  20为字母的高度  index为字母的下标
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)//  减少handletouchMove的执行频率
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
    .list
      display: flex
      flex-direction:column
      justify-content: center
      position: absolute
      top: 1.58rem
      right: 0
      bottom: 0
      width: .4rem
      .item
        line-height: .4rem
        text-align: center
        color: $bgColor
</style>
